﻿using System;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Helpers;
using ChinaDynastyTours.Views.FinanceGroup;
using DevExpress.XtraPrinting;
using System.Drawing;
using ChinaDynastyTours.Assets.DataSet;
using ChinaDynastyTours.Assets;
using IToursDataService.Models;
using IToursDataService;

namespace ChinaDynastyTours.Views
{
    public partial class BillForm : DevExpress.XtraEditors.XtraForm
    {
        private DataTable _dtBillData;
        public string _TourgroupID { get; set; }
        public string _ExpenseID { get; set; }
        public string _ExpenseStatus { get; set; }
        public int _CurrentDisplaySchedulePageNumber { get; set; }

        public BillForm()
        {
            InitializeComponent();
        }

        private void AccountManagerForm_Load(object sender, EventArgs e)
        {
            btnRefresh.PerformClick();

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            _dtBillData = WcfClient.UseService((IToursDataService.IBillCtrl b) => (b.GetBillData(_TourgroupID, ApplicationHelper.CurrentLoginProviderNameAndID[1])));//BillCtrl.GetBillData(_TourgroupID, ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            _dtBillData.RowChanged += new DataRowChangeEventHandler(Table_RowChanged);
            billGridControl.DataSource = _dtBillData;
            lblStatus.Text = _ExpenseStatus;
            switch (_ExpenseStatus)
            {
                case "计划":
                //case "地接提交":
                //case "待审核":
                    billGridView.OptionsBehavior.Editable = true;
                    btnAdd.Enabled = true;
                    btnAudit.Enabled = true;
                    btnDelete.Enabled = true;
                    break;
                default:
                    billGridView.OptionsBehavior.Editable = false;
                    btnAdd.Enabled = false;
                    btnAudit.Enabled = false;
                    btnDelete.Enabled = false;
                    break;
            }
        }

        private void btnAudit_Click(object sender, EventArgs e)
        {
            if (billGridView.FocusedRowHandle < 0) return;

            //如果是‘计划’状态则可以提交
            if (WcfClient.UseService<IExpensesCtrl, bool>(ec => ec.GetAllExpenseStatusForBill(_TourgroupID, ApplicationHelper.CurrentLoginProviderNameAndID[1])))//ExpensesCtrl.GetAllExpenseStatusForBill(_TourgroupID, ApplicationHelper.CurrentLoginProviderNameAndID[1]))
            {
                WcfClient.UseService<IExpensesCtrl>(ec => ec.UpdateExpenseStatusData(_ExpenseID, ExpenseStatusEnum.地接提交));//ExpensesCtrl.UpdateExpenseStatusData(_ExpenseID, ExpenseStatusEnum.地接提交);
                _ExpenseStatus = ExpenseStatusEnum.地接提交.ToString();
                btnRefresh.PerformClick();
            }
            else
                MessageBox.Show(string.Format("当前状态为{0}，不能提交",billGridView.GetRowCellValue(0,"Status")), "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {

            BillItemForm billItemForm = new BillItemForm();
            if (billItemForm.ShowDialog(this) == DialogResult.OK)
            {
               
                #region 计入流水账
                BillEntity entity = new BillEntity();
                //entity.Amount = decimal.Parse(billItemForm.tbAmount.EditValue.ToString());
                entity.ExpenseID =int.Parse(_ExpenseID);
                entity.PeopleNumber = int.Parse(billItemForm.tbPeopleNumber.EditValue.ToString());
                entity.Quantum = decimal.Parse(billItemForm.tbQuantum.EditValue.ToString());
                entity.UnitPrice = decimal.Parse(billItemForm.tbUnitPrice.EditValue.ToString());
                entity.ExpenseType = billItemForm.tbExpenseType.EditValue.ToString();
                entity.ProviderID = int.Parse(ApplicationHelper.CurrentLoginProviderNameAndID[1]);
                entity.Remark = billItemForm.tbRemark.Text;
                entity.TourgroupID = _TourgroupID;


                WcfClient.UseService<IToursDataService.IBillCtrl>(b => b.CreateBillData(entity)); //BillCtrl.CreateBillData(entity);
                #endregion

                btnRefresh.PerformClick();//刷新
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (billGridView.FocusedRowHandle < 0) return;

            if (!WcfClient.UseService<IExpensesCtrl,bool>(ec => ec.GetAllExpenseStatusForBill(_TourgroupID, ApplicationHelper.CurrentLoginProviderNameAndID[1])))//ExpensesCtrl.GetAllExpenseStatusForBill(_TourgroupID, ApplicationHelper.CurrentLoginProviderNameAndID[1]))
            {
                MessageBox.Show("当前状态为非‘计划’或‘地接提交’状态，不能删除！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (MessageBox.Show("确定删除当前选择的信息吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string BillID = billGridView.GetRowCellValue(billGridView.FocusedRowHandle, "BillID").ToString();
                billGridView.DeleteRow(billGridView.FocusedRowHandle);
                WcfClient.UseService<IToursDataService.IBillCtrl>(b => b.DeleteBillData(BillID));//BillCtrl.DeleteBillData(BillID);
            }
        }
        void Table_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change || e.Action == DataRowAction.ChangeCurrentAndOriginal || e.Action == DataRowAction.ChangeOriginal)
            {
                string billID = billGridView.GetRowCellValue(billGridView.FocusedRowHandle, "BillID").ToString();

                BillEntity entity = new BillEntity()
                {
                    BillID = int.Parse(billGridView.GetRowCellValue(billGridView.FocusedRowHandle, "BillID").ToString()),
                    Quantum = e.Row["Quantum"].ToString() == "" ? 0 : decimal.Parse(e.Row["Quantum"].ToString()),
                    UnitPrice = e.Row["UnitPrice"].ToString() == "" ? 0 : decimal.Parse(e.Row["UnitPrice"].ToString()),
                    PeopleNumber = e.Row["PeopleNumber"].ToString() == "" ? 0 : int.Parse(e.Row["PeopleNumber"].ToString()),
                    ExpenseType = e.Row["ExpenseType"].ToString(),
                    Remark = e.Row["Remark"].ToString(),
                };
                WcfClient.UseService<IToursDataService.IBillCtrl>(b => b.UpdateBillData(entity)); //BillCtrl.UpdateBillData(entity);
            }
        }

        private void AccountManageForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //激发行程计划的GrideView数据更新
            if (billGridView.FocusedRowModified)
                billGridView.FocusedRowHandle = billGridView.FocusedRowHandle == 0 ? 1 : 0;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnPrintPreview_Click(object sender, EventArgs e)
        {

            BillDataSet billDs = new BillDataSet();

            foreach (DataRow dr in (billGridControl.DataSource as DataTable).Rows)
            {
                billDs.Tables["fee_Bill"].ImportRow(dr);
            }
            DataTable dtTourgroup = WcfClient.UseService<ITeamGroupCtrl, DataTable>(t => t.GetTeamGroupDataForSchedulePrint(_TourgroupID)); //TeamGroupCtrl.GetTeamGroupDataForSchedulePrint(_TourgroupID);
            foreach (DataRow dr in dtTourgroup.Rows)
            {
                billDs.Tables["TourGroup"].ImportRow(dr);
            }
            //DataTable dtProvider = WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.GetProviderTableDataByID(ApplicationHelper.CurrentLoginProviderNameAndID[1]))); //BaseInfoCtrl.GetProviderTableDataByID(ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            DataTable dtProvider = WcfClient.UseService<IBaseInfo,DataTable>(b=> b.GetProviderTableDataByID(ApplicationHelper.CurrentLoginProviderNameAndID[1])); //BaseInfoCtrl.GetProviderTableDataByID(ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            foreach (DataRow dr in dtProvider.Rows)
            {
                billDs.Tables["Provider"].ImportRow(dr);
            }

            BillReport billRpt = new BillReport();
            billRpt.DataSource = billDs;

            LocalPlanScheduleDataSet scheduleDs = new LocalPlanScheduleDataSet();
            DataTable dtSchedule = WcfClient.UseService<ILocalTeamGroupCtrl,DataTable>(l => l.GetLocalPlanScheduleForBillPrint(_TourgroupID, _CurrentDisplaySchedulePageNumber, ApplicationHelper.CurrentLoginProviderNameAndID[1]));//LocalTeamGroupCtrl.GetLocalPlanScheduleForBillPrint(_TourgroupID, _CurrentDisplaySchedulePageNumber, ApplicationHelper.CurrentLoginProviderNameAndID[1]);
            foreach (DataRow dr in dtSchedule.Rows)
            {
                dr["Date"] = DateTime.Parse(dr["Date"].ToString()).ToString("yy-MM-dd ddd");
                dr["Time"] = DateTime.Parse(dr["Time"].ToString()).ToString("HH:mm");
                scheduleDs.Tables["LocalPlanSchedule"].ImportRow(dr);
            } 
            LocalScheduleReport scheduleRtp = new LocalScheduleReport();
            scheduleRtp.DataSource = scheduleDs;
            billRpt.ScheduleSubRpt.ReportSource = scheduleRtp;
            billRpt.ShowPreviewDialog();

            #region 简易打印
            //PrintableComponentLink pcl = new PrintableComponentLink(printingSystem1);
            //pcl.Component = billGridControl;

            //PageHeaderFooter phf = pcl.PageHeaderFooter as PageHeaderFooter;
            //// Clear the PageHeaderFooter's contents.
            //phf.Header.Content.Clear();
            //// Add custom information to the link's header.
            //phf.Header.Content.AddRange(new string[] { string.Empty, "对账单" });
            //phf.Header.LineAlignment = BrickAlignment.Far;
            //phf.Header.Font = new System.Drawing.Font("宋体", 25, FontStyle.Bold);
            ////pcl.CreateDocument();
            //pcl.ShowPreviewDialog(); 
            #endregion
        }
    }
}
